package com.geostar.constructionland.statistics.service;

import com.geostar.constructionland.common.entity.statistics.LogStatistics;
import com.geostar.constructionland.common.entity.statistics.StatisticsProfile;
import com.geostar.constructionland.statistics.enumeration.StatisticStatus;
import com.geostar.constructionland.statistics.enumeration.TaskResult;
import com.geostar.constructionland.statistics.enumeration.TaskStatus;
import com.geostar.constructionland.statistics.util.TaskObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 异步的消费者线程任务
 *
 * @Author zhu_jiacheng
 * @Date:2020/7/15 12:19
 */
@Service
@Slf4j
public class AsyncConsumerService {

    @Autowired
    private LogStaticService logStaticService;

    // 异步任务，执行将统计sql插入到新表的过程
    @Async("taskExecutor")
    public CompletableFuture<String> generateStatisticTable(TaskObject taskObject) {
        // 获得执行语句，
        StatisticsProfile profile = (StatisticsProfile) taskObject.getTask();
        LogStatistics taskLog = (LogStatistics) taskObject.getOther();
        String sql = profile.getExecuteSql();
        if (sql.contains(";")) {
            sql = sql.replace(";", "");
        }
        LogStatistics logStatistics = logStaticService.getById(taskLog.getId());
        Long timeCost = System.currentTimeMillis();
        try {
            // 执行统计语句，生成新表
            logStaticService.executeSql(sql);
            logStatistics.setResult(TaskResult.SUCCEED.getValue());
        } catch (Exception e) {
            logStatistics.setResult(TaskResult.FAILED.getValue());
            logStatistics.setErrorMsg(e.getMessage());
        } finally {
            // 更新数据库中统计记录的状态
            timeCost = System.currentTimeMillis() - timeCost;
            logStatistics.setStatus(StatisticStatus.DOING.getValue());
            logStatistics.setCostTimeQueue(timeCost + "毫秒");
            logStaticService.updateEntity(logStatistics);
            taskObject.setTaskStatus(TaskStatus.COMPLETED);
        }

        return CompletableFuture.completedFuture(logStatistics.getId());
    }

    //
    @Async("taskExecutor")
    public void handleResult(CompletableFuture<String> futureResult) {
        try {
            String result = futureResult.get();
            // 执行完毕，根据返回的uuid去获取对应的执行记录，更新查询状态
            LogStatistics logStatistics = logStaticService.getById(result);
            logStatistics.setStatus(StatisticStatus.DONE.getValue());
            logStaticService.updateEntity(logStatistics);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
